package middleware

import (
	"coursedesign/projectGo/common"
	"coursedesign/projectGo/model"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func AuthMiddleware() gin.HandlerFunc { // 如何获取上下文？没有参数传给他啊！！！
	return func(context *gin.Context) {
		// 从上下文获取authorization header
		tokenString := context.GetHeader("Authorization")

		// 验证token格式
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer") {
			context.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足"})
			context.Abort()
			return
		}

		tokenString = tokenString[7:]
		token, claims, err := common.ParseToken(tokenString) // 序列化token
		if err != nil || !token.Valid {
			context.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足"})
			context.Abort()
			return
		}

		// 验证通过后获取claim中的userPhone
		userPhone := claims.Id
		DB := common.GetDB()
		var manager model.Manager
		result := DB.First(&manager, userPhone)

		// 用户不存在
		if result.RowsAffected == 0 {
			context.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足"})
			context.Abort()
			return
		}

		// 用户存在 将user信息写入上下文
		context.Set("user", manager)

		context.Next()
	}

}
